#include "http_server.h"
#include "../log.h"
#include "http.h"
#include "http_session.h"
#include "servlet.h"
#include <cstring>
#include <memory>

namespace MYHTTP
{



HttpServer::HttpServer(bool keepalive
            ,IOManager* worker
            ,IOManager* io_worker
            ,IOManager* accept_worker)
:m_isKeepalive(keepalive)
{
    m_dispatch.reset(new ServletDispatch);
}

//设置服务器名称
void HttpServer::setName(const std::string& v)
{
    TcpServer::setName(v);
}

//客户端连接成功的回调函数  处理新连接的Socket类
void HttpServer::handleClient(Socket::ptr client)
{
    log_debug("http server headle client: {}", client->toString());
    HttpSession::ptr session = std::make_shared<HttpSession>(client);

    while(true)
    {
        //解析http请求
        HttpRequest::ptr req = session->recvRequest();
        if(!req)
        {
            log_error("recv http request fail, errno:{}, errstr:{}, client:{}, keep_alive:{}",
                errno, strerror(errno), client->toString(), m_isKeepalive);
            break;
        }

        HttpResponse::ptr rsp = std::make_shared<HttpResponse>
            (req->getVersion(), req->isClose() || !m_isKeepalive);    

        // rsp->setBody("hello world");
        // log_critical("request: {}", req->toString());
        // log_critical("response: {}", rsp->toString());
        m_dispatch->handle(req, rsp, session);
        session->sendResponse(rsp);

        if(!m_isKeepalive || req->isClose())
        {
            break;
        }
    }
    session->close();
}

} //MYHTTP